package com.practice.template;

import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import com.practice.xml.Company;
import com.practice.xml.XmlProcessor;
import com.practice.xml.jaxb.JaxbXmlProcessor;

public class VelocityPractice {

	private static VelocityEngine velocityEngine;
	
	static {
		velocityEngine = new VelocityEngine();
		velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
		velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
		velocityEngine.init();
	}
	
	
	public static void main(String[] args) {
		Template template = velocityEngine.getTemplate("VelocityTemplate.vm");
		//Template template = velocityEngine.getTemplate("VelocityTemplateSAX.vm");
		VelocityContext velocityContext = new VelocityContext();
		
		Writer writer = new StringWriter();
		velocityContext.put("company", xmlParse());
		//velocityContext.put("company", saxParse());
		template.merge(velocityContext, writer);
		
		System.out.println(writer.toString());
	}
	
	public static Company xmlParse() {
		XmlProcessor xmlProcessor = new JaxbXmlProcessor();
		Company company = xmlProcessor.parseXml("company.xml");
		return company;
	}
	
	public static Element saxParse() {
		StringBuilder xmlBuilder = new StringBuilder();
		int bufferSize = 0x400;
		char[] charBuffer = new char[bufferSize];
		int readLength = -1;
		try (FileReader reader = new FileReader("company.xml")) {
			while ((readLength = reader.read(charBuffer, 0, bufferSize)) > -1) {
				xmlBuilder.append(charBuffer, 0, readLength);
			}
		} catch (IOException ex) {
			ex.printStackTrace();
			return null;
		}

		String xmlValue = xmlBuilder.toString();

		SAXBuilder builder;
		Document root = null;
		InputStream inputStream = null;

		builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");

		try {
			inputStream = new ByteArrayInputStream(xmlValue.getBytes("UTF-8"));
			root = builder.build(inputStream);
		} catch (JDOMException | IOException ex) {
			ex.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}

		Element company = null;
		if (root != null) {
			company = root.getRootElement();
		}
		
		return company;
	}

}
